/*
 下载歌曲封面
 */

#import "ImageDownloader.h"
#import "Song.h"

@implementation ImageDownloader

@synthesize song = _song;
@synthesize indexPathInTableView = _indexPathInTableView;
@synthesize delegate = _delegate;
@synthesize activeDownload = _activeDownload;
@synthesize imageConnection = _imageConnection;

#pragma mark

- (void)dealloc
{
    [_song release];
    [_indexPathInTableView release];
    [_activeDownload release];
    
    [_imageConnection cancel];
    [_imageConnection release];
    
    [super dealloc];
}

- (void)startDownload
{
    self.activeDownload = [NSMutableData data];
	
    // alloc+init and start an NSURLConnection; release on completion/failure
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:
                             [NSURLRequest requestWithURL:
                              [NSURL URLWithString:self.song.coverArt]] delegate:self];
    self.imageConnection = conn;
    [conn release];
}

- (void)cancelDownload
{
    [self.imageConnection cancel];
    self.imageConnection = nil;
    self.activeDownload = nil;
}


#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.activeDownload appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	// Clear the activeDownload property to allow later attempts
    self.activeDownload = nil;
    
    // Release the connection now that it's finished
    self.imageConnection = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	// 下载的数据其实是一张图片
    UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];

	// 保存图片
	NSString *coverPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[self.song.coverArt lastPathComponent]];
    [[NSFileManager defaultManager] createFileAtPath:coverPath contents:UIImageJPEGRepresentation(image, 1.0f) attributes:nil];

	// 缓存到歌曲信息中。
	self.song.coverImage = image;
    
	// Clear the activeDownload property to allow later attempts
    self.activeDownload = nil;
    [image release];
    
    // Release the connection now that it's finished
    self.imageConnection = nil;
    
    // 调用协议的方法，图片已经下载完毕，准备显示出来吧。
    [self.delegate imageDidLoad:self.indexPathInTableView];
}

@end